package com.dotflat.physicalevaluate.service.impl.chart;

import com.dotflat.physicalevaluate.service.RemoteHighChartService;
import com.matt.commons.exception.BusinessException;
import com.matt.foundation.model.ErrorCode;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.beans.factory.annotation.Value;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.util.Map;

public abstract class  AbstractRemoteHighChartService implements RemoteHighChartService {

    @Value("${server.chart.url}")
    protected String chartServerURL = "http://charts.tuo51.com";

    protected byte[] binaryHTTPCall(String url, String json, String errorMsg) {
        try {

            byte[] responseData = sendPostJson(url, json, "UTF-8");

            return responseData;
        } catch (BusinessException e){
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ErrorCode.UNDEFINED, errorMsg);
        }
    }

    @Override
    public String getRemoteEvaluateChartBase64(Map dataMap) {
        byte[] result = getRemoteEvaluateChart(dataMap);

        String data = DatatypeConverter.printBase64Binary(result);

        return data;
    }

    public byte[] sendPostJson(String url, String params, String charset) throws IOException {
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestHeader("Content-Type", "application/json; charset=" + charset);
        if (params != null && !params.trim().equals("")) {
            RequestEntity requestEntity = new StringRequestEntity(params, "application/json", charset);
            postMethod.setRequestEntity(requestEntity);
        }

        HttpClient httpClient = new HttpClient();
        httpClient.executeMethod(postMethod);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(120000);
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(120000);
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(10,true));


        byte[] result = postMethod.getResponseBody();
        System.out.println("status code return by httpCLient is "+postMethod.getStatusCode());

//        String ret = String.valueOf(result);
//        System.out.println("chart result:\n" + ret);

        return result;
    }

}
